package org.example;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class ExampleMain {
    public static void main(String[] args) {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("my-persistence-unit");
        EntityManager em = emf.createEntityManager();
        nativeQuery(em,"SHOW TABLES");
        nativeQuery(em,"SHOW COLUMNS FROM CUSTOMER");
        nativeQuery(em,"SHOW COLUMNS FROM ORDERS");
        persisCustomer(em);
        nativeQuery(em,"Select * from Customer");
        nativeQuery(em,"SELECT * FROM ORDERS");
        em.close();
    }

    private static void persisCustomer(EntityManager em){
        Customer customer1 = new Customer();
        customer1.setName("Lindsey Craft");
        customer1.addOrder("online","XYZ Blender",2);
        customer1.addOrder("store","ZZZ Beer Glass",4);

        Customer customer2 = new Customer();
        customer2.setName("Morgan Philips");
        customer2.addOrder("online","AA Glass Cleaner",3);
        em.getTransaction().begin();
        em.persist(customer1);
        em.persist(customer2);
        em.getTransaction().commit();

    }
    public static void nativeQuery(EntityManager em,String s){
        System.err.println("-----------------------" + s + "-----------------------");
        Query query = em.createNativeQuery(s);
        List list = query.getResultList();
        for (Object o : list) {
           if(o instanceof Object[]){
               System.err.println(Arrays.asList((Object[]) o));
           }else{
               System.err.println(o);
           }
        }
        System.err.println("-------------------------------------");

    }
}
